package hadoop.mr07;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.lib.db.DBWritable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class stuTable implements Writable, DBWritable {
    private String id;
    private String name;
    private String sex;
    private String class_;
    private String ability;

    public stuTable() {
    }

    public stuTable(String id, String name, String sex, String class_, String ability) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.class_ = class_;
        this.ability = ability;
    }

    public void set(String id, String name, String sex, String class_, String ability) {
        this.id = id;
        this.name = name;
        this.sex = sex;
        this.class_ = class_;
        this.ability = ability;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getClass_() {
        return class_;
    }

    public void setClass_(String class_) {
        this.class_ = class_;
    }

    public String getAbility() {
        return ability;
    }

    public void setAbility(String ability) {
        this.ability = ability;
    }

    // 序列化
    @Override
    public void write(DataOutput dataOutput) throws IOException {
        dataOutput.writeUTF(id);
        dataOutput.writeUTF(name);
        dataOutput.writeUTF(sex);
        dataOutput.writeUTF(class_);
        dataOutput.writeUTF(ability);
    }

    // 反序列化
    @Override
    public void readFields(DataInput dataInput) throws IOException {
        this.id = dataInput.readUTF();
        this.name = dataInput.readUTF();
        this.sex = dataInput.readUTF();
        this.class_ = dataInput.readUTF();
        this.ability = dataInput.readUTF();
    }

    // 获取数据库字段
    @Override
    public void write(PreparedStatement ps) throws SQLException {
        // 与数据库字段类型一致
        ps.setInt(1,Integer.parseInt(id));
        ps.setString(2,name);
        ps.setString(3,sex);
        ps.setString(4,class_);
        ps.setString(5,ability);

    }

    // 获取查询的结果
    @Override
    public void readFields(ResultSet rs) throws SQLException {
        // 将获取的值添加给类属性
        this.id = String.valueOf(rs.getInt(1));
        this.name = rs.getString(2);
        this.sex = rs.getString(3);
        this.class_ = rs.getString(4);
        this.ability = rs.getString(5);
    }

    @Override
    public String toString() {
        return id+" "+name+" "+sex+" "+class_+" "+ability;
    }
}
